package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

import processing.core.PApplet;

public class DBConnector {
	
	private AlbumCollection albumCollection;
	private PApplet parent;
	
	public DBConnector(PApplet parent){
		albumCollection = new AlbumCollection();
		this.parent = parent;
		
		try
		{
		  Class.forName("com.mysql.jdbc.Driver").newInstance();
		  String url = "jdbc:mysql://localhost/iphone";
		  conn = DriverManager.getConnection(url, "root", "");
		  
		}
		catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());}
	    catch (IllegalAccessException ex) {System.err.println(ex.getMessage());}
	    catch (InstantiationException ex) {System.err.println(ex.getMessage());}
	    catch (SQLException ex)           {System.err.println(ex.getMessage());}

	}
	
	public void doTests(){
		System.out.println("[OUTPUT FROM SELECT]");
	    String query = "SELECT artist, album, price, userid, latitude, longtitude, store, time FROM items";
	    try
	    {
	      Statement st = conn.createStatement();
	      ResultSet rs = st.executeQuery(query);
	      while (rs.next())
	      {
	        String title = rs.getString("album");
	        float price = rs.getFloat("price");
	        String artist = rs.getString("artist");
	        
	        // search for album url, other data from last fm
	        // -> then create album
	        Album newAlbum = new Album(this);
	        newAlbum.setArtist(artist);
	        newAlbum.setTitle(title);
	        Vector<String> tracks = new Vector<String>();
	        tracks.add("track1");
	        tracks.add("track2");
	        newAlbum.setTracks(tracks);
	        String imageUrl = "http://sleevage.com/wp-content/uploads/2007/08/coldplay_xy_album_front.gif";
	        newAlbum.setImage(imageUrl);
	        albumCollection.addAlbum(newAlbum);
	      }
	    }
	    catch (SQLException ex)
	    {
	      System.err.println(ex.getMessage());
	    }

	}
	
	public void close(){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Connection conn;

	public PApplet getParent() {
		return parent;
	}

	public AlbumCollection getAlbumCollection() {
		return albumCollection;
	}


	
}
